package net.xuele.learn.executorPool;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @Author: yubo
 * @date: 16:40 2021/2/26
 * @Description: 类描述
 */

public class RecycleExecutor extends ThreadPoolExecutor {

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        if (r instanceof AbstractStatefulRunnable) {
            AbstractStatefulRunnable runnable = (AbstractStatefulRunnable) r;
            if (!runnable.isSuccess()) {
                try {
                    this.getQueue().offer(runnable, 100, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    // todo：这个中断异常应该怎么处理呢？？？
                    e.printStackTrace();
                }
            }
        }

    }

    public RecycleExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    static abstract class AbstractStatefulRunnable implements Runnable {

        private boolean isSuccess = false;

        public boolean isSuccess() {
            return isSuccess;
        }

        @Override
        public void run() {
            isSuccess = doRun();
        }

        /**
         * run
         * @return true means the task execute successfully
         */
        protected abstract boolean doRun();
    }


    /**
     * 测试代码
     *
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        RecycleExecutor recycleExecutor = new RecycleExecutor(2, 10, 10,
                TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
        CountDownLatch l = new CountDownLatch(1);
//        recycleExecutor.execute(new AbstractStatefulRunnable(){
//
//            @Override
//            protected boolean doRun() {
//                return false;
//            }
//        });

            String code = String.format(
                    // decorate to TTL wrapper,
                    // and then set AutoWrapper attachment/Tag
                    "    $%d = %s.get($%1$d, false, true);"
                            + "\n    com.alibaba.ttl.spi.TtlAttachmentsDelegate.setAutoWrapperAttachment($%1$d);",
                    5, "333");
            System.out.println(code);

        l.await();
    }

}
